package org.arch_learn.io.netty_demo.chatroom;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.SocketAddress;
import java.util.Scanner;

public class NettyChatClient {
    //服务端ip
    private String ip;
    //服务端端口
    private Integer port;

    public NettyChatClient(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
    }

    public void run() {
        NioEventLoopGroup group = null;
        try {
            //1.创建线程组
            group = new NioEventLoopGroup(10);
            //2.创建客户端启动助手
            Bootstrap bootstrap = new Bootstrap();
            //3.设置线程组
            bootstrap.group(group)
                    //4.设置客户端通道实现为NIO
                    .channel(NioSocketChannel.class)
                    //5.创建一个通道初始化对象
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //6.向pipeline中添加自定义业务处理handler
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加解码器
                            pipeline.addLast("messageDecoder", new StringDecoder());
                            //添加编码器
                            pipeline.addLast("messageEncoder", new StringEncoder());
                            //pipeline.addLast(new MessageCodec());
                            pipeline.addLast(new NettyChatClientHandler());
                        }
                    });
            //7.启动客户端，等待连接服务器，同时将异步改成同步
            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
            Channel channel = channelFuture.channel();
            SocketAddress socketAddress = channel.localAddress();
            String localAddString = socketAddress.toString().substring(1);
            System.out.println("--------" + localAddString + "-----------");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String nextLine = scanner.nextLine();
                //向服务端发送消息
                channel.writeAndFlush(nextLine);
            }
            //8.关闭通道和关闭连接池
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyChatClient nettyChatClient = new NettyChatClient("127.0.0.1", 9999);
        nettyChatClient.run();
    }
}
